package com.google.code.pj2r.sample.simple.resources;

import java.util.Iterator;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.code.pj2r.DataAccessException;
import com.google.code.pj2r.MarshallingException;
import com.google.code.pj2r.ResourceConflictException;
import com.google.code.pj2r.ResourceException;
import com.google.code.pj2r.sample.simple.dao.StuffDAO;
import com.google.code.pj2r.sample.simple.dao.StuffEntity;

public class DojoStuff extends DojoItemFileStoreResource {

    /**
     * This is used when handling POST data for the create case.
     */
    private String stuff;

    /**
     * Must have a public no-args constructor.
     */
    public DojoStuff() {
    }

    /**
     * Used to get the POSTed data when creating new Stuff.
     * @return
     */
    public String getStuff() {
        return stuff;
    }

    /**
     * Set by the framework to inject POSTed data.
     * @param stuff The POSTed parameter.
     */
    public void setStuff(String stuff) {
        this.stuff = stuff;
    }

    /**
     * We should create a new resource.
     * @return The new ID for the resource.
     * @throws ResourceException If creating the resource fails for some reason.
     */
    public String create() throws DataAccessException {
        // Create a persistent entity
        StuffEntity entity = new StuffEntity();

        // Retrieve the POSTed data and set it on the entity. The POST data is
        // retrieved from the HttpServletRequest and injected by the setXXX
        // methods on this class.
        entity.setValue(getStuff());

        // Persist the new entity
        StuffDAO.getInstance().add(entity);

        // Return the new Entity ID so that the Location header an be created.
        return entity.getId();
    }


    /**
     * Delete a resource
     */
	public void delete(String id) {
		StuffDAO.getInstance().delete(id);
	}

	public String get(String id) throws DataAccessException, MarshallingException {
		StuffEntity entity = StuffDAO.getInstance().get(id);
		String json = null;
		try {
			json = toJSON(entity).toString();
		} catch (JSONException e) {
			throw new MarshallingException(e);
		}
		return json;
	}

	public String list() throws DataAccessException, MarshallingException {
		List result = StuffDAO.getInstance().getAll();
		JSONArray jsonArray = new JSONArray();
		String json = null;
		try {
			for (Iterator i = result.iterator(); i.hasNext();) {
                StuffEntity stuffEntity = (StuffEntity) i.next();
				jsonArray.put(toJSON(stuffEntity));
			}
			json = addDojoRequiredJSON("id", "id", jsonArray).toString();
		} catch (JSONException e) {
			throw new MarshallingException(e);
		}
		return json;
	}

	public void update(String id) throws DataAccessException, ResourceConflictException {
		StuffDAO dao = StuffDAO.getInstance();
        StuffEntity entity = dao.get(id);
		entity.setValue(getStuff());
		// Since the dao is actually a fake it should be enough to mutate
		// the object to make it "persistant"
	}

    private JSONObject toJSON(StuffEntity entity) throws JSONException {
        if (entity != null) {
            JSONObject result = new JSONObject();
            // Hand crafted JSON object.
            result.put("id", entity.getId());
            result.put("stuff", entity.getValue());
            return result;
        }
        return null;
    }

}
